//
//  OrderDetailController.m
//  ios-supplier
//
//  Created by feynmanyuan on 15/4/18.
//  Copyright (c) 2015年 feynmanyuan. All rights reserved.
//

#import "OrderDetailController.h"
#import "AcceptBtnPartialView.h"
#import "RefusePartialView.h"
#import "UserInfoPartialView.h"
#import "PaymentPartialView.h"
#import "MerchandisePartialView.h"
#import "StaffInfoPartialView.h"
#import "JFBRefuseOrderDS.h"
#import "OrderStaffSelectController.h"
#import "IdentifyBtnPartialView.h"
#import "JFBCompleteOrderDS.h"
#import "RefundBtnPartialView.h"
#import "JFBStaffDS.h"

#define cBottomBtnContainerHeight kBottomBtnContainerHeight

@interface OrderDetailController ()<UIActionSheetDelegate, UIAlertViewDelegate,UIGestureRecognizerDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *detailView;
@property (nonatomic, weak) IBOutlet PartialViewBase *btnContainerView;
@property (nonatomic, strong) IBOutlet IdentifyBtnPartialView *btnIdentifyView;
@property (nonatomic, strong) IBOutlet RefundBtnPartialView *btnRefundView;
@property (weak, nonatomic) IBOutlet UserInfoPartialView *userInfoPanelView;
@property (weak, nonatomic) IBOutlet RefusePartialView *masterRefusePanelView;
@property (weak, nonatomic) IBOutlet StaffInfoPartialView *staffPanelView;
@property (weak, nonatomic) IBOutlet PaymentPartialView *paymentPanelView;
@property (weak, nonatomic) IBOutlet MerchandisePartialView *merchandisePanelView;


@property (nonatomic, strong) NSDictionary *refuseRease;

@property (weak, nonatomic) IBOutlet UILabel *orderNumberLabel;
@property (weak, nonatomic) IBOutlet UILabel *createAtLabel;
@property (weak, nonatomic) IBOutlet UILabel *requireTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *cancelTimeLabel;

@end

@implementation OrderDetailController

- (void)dealloc {
    self.refuseRease = nil;
    _btnContainerView = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"orderDetailForAction"  object:nil];
}


- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.refuseRease = @{@"undealer":@[@"超过配送距离", @"商品售空", @"重复订单"], @"deliveries":@[@"客户拒收", @"地址有误", @"联系不到客户"]};
    //监听Bottom Panel的事件
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationAction:) name:@"orderDetailForAction" object:nil];
    
    if( IS_OS_7_OR_LATER ) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
    [self.view addGestureRecognizer:tap];
    
    [self initSubViews];
    
    [self reload:nil];
    
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    
    [self.navigationItem setLeftBarButtonItem: [self createBackView]];
}
#warning item 修改
- (UIBarButtonItem *)createBackView
{
    UIButton *leftButtonItem = [UIButton buttonWithType:UIButtonTypeCustom];
    
    leftButtonItem.frame = CGRectMake(0, 0, 11, 20);
    
    [leftButtonItem setBackgroundImage:[UIImage imageNamed:@"icon-Back"] forState:UIControlStateNormal];
    
    [leftButtonItem setImageEdgeInsets: UIEdgeInsetsMake((19 - 11) / 2, 0, (19 - 11) / 2, 0)];
    
    [leftButtonItem addTarget:self action:@selector(leftButtonItemClicked) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * item = [[UIBarButtonItem alloc] initWithCustomView:leftButtonItem];
    
    return item;
}

-(void)leftButtonItemClicked
{
    [self.navigationController popViewControllerAnimated:YES];
}


-( void )initSubViews{
    self.userInfoPanelView = (UserInfoPartialView*)[self bindXibResource:@"UserInfoPartialView"];
    [self.detailView addSubview:self.userInfoPanelView];
    
    self.paymentPanelView = (PaymentPartialView*)[self bindXibResource:@"PaymentPartialView"];
    [self.detailView addSubview:self.paymentPanelView];
    
    self.merchandisePanelView = (MerchandisePartialView*)[self bindXibResource:@"MerchandisePartialView"];
    [self.detailView addSubview:self.merchandisePanelView];
    
    self.masterRefusePanelView = (RefusePartialView*)[self bindXibResource:@"RefusePartialView"];
    [self.detailView addSubview:self.masterRefusePanelView];
    
    self.staffPanelView = (StaffInfoPartialView*)[self bindXibResource:@"StaffInfoPartialView"];
    [self.detailView addSubview:self.staffPanelView];
    if (_btnContainerView == nil) {
        _btnContainerView = (AcceptBtnPartialView*)[self bindXibResource:@"AcceptBtnPartialView"];
    }
    self.btnIdentifyView = (IdentifyBtnPartialView*)[self bindXibResource:@"IdentifyBtnPartialView"];
    self.btnRefundView = (RefundBtnPartialView*)[self bindXibResource:@"RefundBtnPartialView"];
    
    [self.detailView setBackgroundColor:PanelBgColorDefault];
    
    if ( [self.order.orderType isEqualToString:@"complete"] || [self.order.orderType isEqualToString:@"refuse"] ) {
        self.detailView.frame = CGRectMake(self.detailView.frame.origin.x, self.detailView.frame.origin.y, self.detailView.frame.size.width, self.detailView.frame.size.height + 60);
    }

}


//绑定XIB文件
-(UIView*)bindXibResource:(NSString*)xibName {
    NSArray *views = [[NSBundle mainBundle] loadNibNamed:xibName owner:nil options:nil];
    UIView *bv = [views objectAtIndex:0];
    return bv;
}

-(void)dismissKeyboard {

    if( [self.order.orderType isEqualToString:@"deliveries"] && self.btnIdentifyView.tag == 1 ) {
        for(UIView * v in self.btnIdentifyView.subviews) {
            if( [v isKindOfClass:[UITextField class]] ) {
                [((UITextField*)v) resignFirstResponder];
                break;
            }
        }
    }
}

- (void)reload:(__unused id)sender {

}

- (void)setOrder:(JFBOrderDS*)order{
    _order = order;
    
    self.detailView.frame = CGRectMake(0, 0, self.detailView.frame.size.width, self.view.bounds.size.height - ( ([order.orderType isEqualToString:@"complete"] || [order.orderType isEqualToString:@"refuse"]) ? 0 : cBottomBtnContainerHeight));
    [self showAllHidableView];
    
    NSUInteger contentHeight = 0;
    
    
    if( [order.orderType isEqualToString:@"undealer"] ) {
        //隐藏不需要的Partical View
        self.masterRefusePanelView.hidden = true;
        self.staffPanelView.hidden = true;
        
        // 按序列渲染
        contentHeight = [self viewPartialRenderQueue:@[self.userInfoPanelView, self.paymentPanelView, self.merchandisePanelView] order:order];
        
        [JFBStaffDS getDefaultStaff:^(JFBStaffDS *staff, NSError *error) {
            [self appendBtnContainer:self.btnContainerView order:order];
        }];
        
        self.navigationItem.titleView = [self renderNavTitle:@"未处理"];
    } else if( [order.orderType isEqualToString:@"refuse"] ) {

        self.staffPanelView.hidden = true;
        
        contentHeight = [self viewPartialRenderQueue:@[self.masterRefusePanelView, self.paymentPanelView, self.userInfoPanelView, self.merchandisePanelView] order:order];
        
        self.navigationItem.titleView = [self renderNavTitle:@"拒绝/取消"];
    } else if( [order.orderType isEqualToString:@"deliveries"] ){

        self.masterRefusePanelView.hidden = true;
        
        contentHeight = [self viewPartialRenderQueue:@[self.staffPanelView, self.userInfoPanelView, self.paymentPanelView, self.merchandisePanelView] order:order];
        
        [self appendBtnContainer:self.btnIdentifyView order:order];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
        
        //注册通知,监听键盘消失事件
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHidden) name:UIKeyboardDidHideNotification object:nil];
        
        self.navigationItem.titleView = [self renderNavTitle:@"配送中"];
    } else {

        self.masterRefusePanelView.hidden = true;
        
        contentHeight = [self viewPartialRenderQueue:@[self.staffPanelView, self.paymentPanelView, self.userInfoPanelView, self.merchandisePanelView] order:order];
        
        if (self.isDayDetail) {
            self.navigationItem.title = @"已完成";
        }
        else
        {
            self.navigationItem.titleView = [self renderNavTitle:@"已完成"];
        }
    }
    
    contentHeight = [self reRendeLabels:order contentHeight:contentHeight];
    
    self.detailView.contentSize = CGSizeMake(self.view.bounds.size.width, [order.orderType isEqualToString:@"complete"] ? contentHeight + cBottomBtnContainerHeight : contentHeight + kOrderCellHeaderHeight);
}

-(UIView *)renderNavTitle:(NSString*)title {
    UIView *titleView = [[UIView alloc]init];
    titleView.frame = CGRectMake(0, 0, 100, 30);
    UILabel *statusLabel = [[UILabel alloc]init];
    statusLabel.textColor = [UIColor whiteColor];
    statusLabel.font = [UIFont systemFontOfSize:TextFontSizeH3];
    [statusLabel setTextAlignment:NSTextAlignmentCenter];
    CGSize titleSize = [title sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:TextFontSizeH3]}];
    CGFloat titleY = 0;
    CGFloat titleX = 0;
    CGRect orderNumberRect = CGRectMake(titleX, titleY, 100, titleSize.height);
    statusLabel.text = title;
    statusLabel.frame = orderNumberRect;
    statusLabel.text = title;
    
    NSString *detailStr = @"订单详情";
    UILabel *detailLabel = [[UILabel alloc]init];
    detailLabel.textColor = [UIColor whiteColor];
    detailLabel.font = [UIFont systemFontOfSize:TextFontSizeH4];
    [detailLabel setTextAlignment:NSTextAlignmentCenter];
    CGSize detailSize = [detailStr sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:TextFontSizeH4]}];
    CGFloat detailY = titleY + titleSize.height;
    CGFloat detailX = 0;
    CGRect detailRect = CGRectMake(detailX, detailY, 100, detailSize.height);
    detailLabel.text = title;
    detailLabel.frame = detailRect;
    detailLabel.text = @"订单详情";
    
    [titleView addSubview:statusLabel];
    [titleView addSubview:detailLabel];
    
    return titleView;
}

//渲染尾部标签
-(NSUInteger)reRendeLabels:(JFBOrderDS*)order contentHeight:(NSUInteger)contentHeight {
    
    NSString * orderNumber = [NSString stringWithFormat:@"订单编号：%@", order.orderCode];
    CGSize orderNumberSize = [orderNumber sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:TextFontSizeH4]}];
    CGFloat orderNumberY = contentHeight + kOrderCellSpacing;//(kOrderCellHeaderHeight - requireTimeSize.height) / 2;
    CGFloat orderNumberX = kOrderCellMargin;
    CGRect orderNumberRect = CGRectMake(orderNumberX, orderNumberY, orderNumberSize.width, orderNumberSize.height);
    self.orderNumberLabel.text = orderNumber;
    self.orderNumberLabel.frame = orderNumberRect;
    
    contentHeight += orderNumberSize.height + kOrderCellSpacing;
    
    NSString * createAt = [NSString stringWithFormat:@"下单时间：%@", order.createAt];
    CGSize createAtSize = [createAt sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:TextFontSizeH4]}];
    CGFloat createAtY = contentHeight + kOrderCellSpacing;//(kOrderCellHeaderHeight - requireTimeSize.height) / 2;
    CGFloat createAtX = kOrderCellMargin;
    CGRect createAtRect = CGRectMake(createAtX, createAtY, createAtSize.width, createAtSize.height);
    self.createAtLabel.text = createAt;
    self.createAtLabel.frame = createAtRect;
    
    contentHeight += createAtSize.height + kOrderCellSpacing;
    
    if( [order.orderType isEqualToString:@"refuse"] ) {
        [self.requireTimeLabel removeFromSuperview];
        
        NSString * updateAt = [NSString stringWithFormat:@"取消时间：%@", order.updateAt];
        CGSize updateAtSize = [updateAt sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:TextFontSizeH4]}];
        CGFloat updateAtY = contentHeight + kOrderCellSpacing;//(kOrderCellHeaderHeight - requireTimeSize.height) / 2;
        CGFloat updateAtX = kOrderCellMargin;
        CGRect updateAtRect = CGRectMake(updateAtX, updateAtY, updateAtSize.width, updateAtSize.height);
        self.cancelTimeLabel.text = updateAt;
        self.cancelTimeLabel.frame = updateAtRect;
        
        contentHeight += updateAtSize.height + kOrderCellSpacing;
    } else {
        [self.requireTimeLabel removeFromSuperview];
        [self.cancelTimeLabel removeFromSuperview];
    }
    
    return contentHeight;
}

// 键盘弹出时
-(void)keyboardDidShow:(NSNotification *)notification
{
    //获取键盘高度
    NSValue *keyboardObject = [[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey];
    
    CGRect keyboardRect;
    
    [keyboardObject getValue:&keyboardRect];
    
    //调整放置有textView的view的位置
    
    //设置动画
    //    [UIView beginAnimations:nil context:nil];
    //
    //    //定义动画时间
    //    [UIView setAnimationDuration:kAnimationDuration];
    
    //设置view的frame，往上平移
    [self.btnIdentifyView setFrame:CGRectMake(0, self.view.frame.size.height-keyboardRect.size.height-60, self.view.bounds.size.width, 60)];
    //标记btnIdentityView 用于点击空白处收起键盘的判断
    self.btnIdentifyView.tag = 1;
    //    [UIView commitAnimations];
}

-(void)keyboardDidHidden
{
    //定义动画
    //    [UIView beginAnimations:nil context:nil];
    //    [UIView setAnimationDuration:kAnimationDuration];
    //设置view的frame，往下平移
    [self.btnIdentifyView setFrame:CGRectMake(0, self.view.frame.size.height - 60, self.view.bounds.size.width, 60)];
    //标记btnIdentityView 用于点击空白处收起键盘的判断
    self.btnIdentifyView.tag = 0;
    //    [UIView commitAnimations];
}

-(void)appendBtnContainer:(PartialViewBase*)view order:(JFBOrderDS*)order{
    [self.view addSubview:view];
    view.frame = CGRectMake(0, self.view.bounds.size.height - cBottomBtnContainerHeight, self.view.bounds.size.width, cBottomBtnContainerHeight);
    view.order = order;
    view.frame = CGRectMake(0, self.view.bounds.size.height - cBottomBtnContainerHeight, self.view.bounds.size.width, cBottomBtnContainerHeight);
}

-(void)showAllHidableView{
    self.masterRefusePanelView.hidden = false;
    self.staffPanelView.hidden = false;
}

- (NSUInteger)viewPartialRenderQueue:(NSArray*)queue order:(JFBOrderDS*)order {
    NSUInteger contentHeight = 0;
    for( PartialViewBase *baseView in queue ) {
        contentHeight += [self viewPartialExpand:baseView order:order contentHeight:contentHeight];
    }
    return contentHeight;
}

- (NSUInteger)viewPartialExpand:(PartialViewBase*)view order:(JFBOrderDS*)order contentHeight:(NSUInteger)contentHeight {
    view.frame = CGRectMake(0, contentHeight + kOrderCellSpacing, self.view.bounds.size.width, view.height);
    view.order = order;
    view.frame = CGRectMake(0, contentHeight + kOrderCellSpacing, self.view.bounds.size.width, view.height);
    return view.height + kOrderCellSpacing;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)notificationAction:(NSNotification *)notification {
    NSString * eventType = [notification.userInfo objectForKey:@"event"];
    if( [eventType isEqualToString:@"refuse"]) {
        //选择拒单理由
        NSArray * array = _refuseRease[self.order.orderType];
        if ([array count]) {
             UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"选择理由"
                                                       delegate:self
                                              cancelButtonTitle:@"取消"
                                         destructiveButtonTitle:nil
                                              otherButtonTitles:nil, nil];
            for( NSString * title in [self.refuseRease objectForKey:self.order.orderType] ) {
                [actionSheet addButtonWithTitle:title];
            }
            [actionSheet showInView:self.view];
        }
    } else if( [eventType isEqualToString:@"accept"] ) {
        JFBStaffDS *staff = [JFBStaffDS loadFromDB];
        //同意由默认配送员配送
        [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeBlack];
        [JFBOrderDS acceptStaff:^(BOOL isSuccess, JFBOrderDS *order, NSError *error) {
            [SVProgressHUD dismiss];
            [self forAlertTips:isSuccess ? @"操作成功" : @"失败，请稍候重试或致电客服"];
        } orderID:self.order.ID staffID:staff.Id];
    } else if([eventType isEqualToString:@"verify"]){
        NSString *code = [notification.userInfo objectForKey:@"code"];
        
        //校验验证码
        [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeBlack];
        [JFBCompleteOrderDS verifyIdentifyCode:^(BOOL isSuccess, JFBOrderDS *order, NSString *message, NSError *error) {
            [SVProgressHUD dismiss];
            if( isSuccess ) {
                [self.view endEditing:YES];
                [self forAlertTips:message];
            } else {
                [JFBUIAnimation alertTips:message];
            }
        } orderID:self.order.ID identifyCode:code];
    } else if([eventType isEqualToString:@"refund"]){
        //退款
        [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeBlack];
        [JFBRefuseOrderDS refund:^(BOOL isSuccess, JFBOrderDS *order, NSString *message, NSError *error) {
            [SVProgressHUD dismiss];
            [self forAlertTips:message];
        } orderID:self.order.ID];
    } else {
        //选择配送员
        [self performSegueWithIdentifier:@"orderStaffSelectSceneIdentifier" sender:self];
    }
    
}

-(void)forAlertTips:(NSString*)msg {
    if (IS_OS_8_OR_LATER) {
        UIAlertController *alertCtrl = [UIAlertController alertControllerWithTitle:@"提示" message:msg preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            [self.navigationController popViewControllerAnimated:YES];
            [self.refreshDelegate reload];
        }];
        [alertCtrl addAction:okAction];
        [self presentViewController:alertCtrl animated:YES completion:nil];
    }else{
        //这个else一定要写，否则会导致在ios8一下的真机crash
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:msg delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        alert.tag = 998;
        [alert show];
    }
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if( [segue.identifier isEqualToString:@"orderStaffSelectSceneIdentifier"] ) {
        OrderStaffSelectController * controller = (OrderStaffSelectController*)segue.destinationViewController;
        controller.order = self.order;
        controller.refreshDelegate = self.refreshDelegate;
    }
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if( buttonIndex == actionSheet.cancelButtonIndex ) {
        return;
    }
    NSArray *reason = [self.refuseRease objectForKey:self.order.orderType];
    [JFBRefuseOrderDS refuse:^(BOOL isSuccess, JFBRefuseOrderDS *order, NSError *error) {
        [JFBUIAnimation alertSure:isSuccess ? @"操作成功" : @"失败，请稍候重试或致电客服" delegate:self];
        
    } orderID:self.order.ID reason:reason[buttonIndex - 1]];
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    // NSString *btnTitle =
//    [alertView buttonTitleAtIndex:buttonIndex];
    
    [self.navigationController popViewControllerAnimated:TRUE];
    [self.refreshDelegate reload];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    
    [self.view endEditing:YES];
    
    [super touchesBegan:touches withEvent:event];
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
